package com.my.ribbon;

import cn.hutool.http.HttpUtil;
import com.google.common.collect.Lists;
import com.netflix.client.DefaultLoadBalancerRetryHandler;
import com.netflix.client.RetryHandler;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.LoadBalancerBuilder;
import com.netflix.loadbalancer.Server;
import com.netflix.loadbalancer.reactive.LoadBalancerCommand;
import rx.Observable;

import java.util.List;

/**
 * @author Zijian Liao
 * @since ribbon demo
 */
public class RibbonDemo {

    public static void main(String[] args) throws Exception {
        // 重试handler 第一个参数为调用同一个实例的次数，第二个为再次尝试调用其他实例的个数，1就是调用失败后，换一个实例再来一次，还是失败就返回失败。
        final RetryHandler retryHandler = new DefaultLoadBalancerRetryHandler(1, 1, true);
        List<Server> serverList = Lists.newArrayList(
                new Server("127.0.0.1", 8081),
                new Server("127.0.0.1", 8084));
        // 创建一个负载均衡器，默认负载均衡算法为轮询
        ILoadBalancer loadBalancer = LoadBalancerBuilder.newBuilder()
                .buildFixedServerListLoadBalancer(serverList);
        for (int i = 0; i < 6; i++) {
            String result = LoadBalancerCommand.<String>builder()
                    .withLoadBalancer(loadBalancer)
                    .withRetryHandler(retryHandler)
                    .build()
                    .submit(server -> {
                        String url = "http://" + server.getHost() + ":" + server.getPort() + "/goods/get";
                        return Observable.just(HttpUtil.get(url));
                    }).toBlocking().first();
            System.out.println(result);
        }
    }
}
